package cn.momoshenchi.medicine.controller;

import cn.momoshenchi.medicine.enumerate.Add;
import cn.momoshenchi.medicine.enumerate.Update;
import cn.momoshenchi.medicine.pojo.BaseDrug;
import cn.momoshenchi.medicine.service.BaseDrugService;
import cn.momoshenchi.medicine.util.AssertUtil;
import cn.momoshenchi.medicine.util.PageUtil;
import cn.momoshenchi.medicine.util.ResultInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.awt.print.Book;
import java.util.List;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/7/13 - 14:09
 */
@RestController()
@RequestMapping("/drug")
public class DrugController
{
    @Autowired
    private BaseDrugService baseDrugService;


    /**
     * 分页查询药品数据
     *
     * @return
     */
    @GetMapping("/page")
    public ResultInfo list(PageUtil page)
    {
        IPage<BaseDrug> drugPage = new Page<>(page.getPage(), page.getSize());
        drugPage = baseDrugService.page(drugPage);
        return new ResultInfo(drugPage);

    }

    /**
     * 根据关键字(拼音)搜索药品pinyin_code
     * 特殊要求,-1需要返回所有药品(不分页了)
     *
     * @return
     */
    @GetMapping("/search/{keyword}")
    public ResultInfo search(@PathVariable String keyword)
    {
        List<BaseDrug> baseDrugList = null;
        if (("-1").equals(keyword.strip()))
        {
            baseDrugList = baseDrugService.list();
        }
        else
        {
            baseDrugList = baseDrugService.list(new QueryWrapper<BaseDrug>()
                    .like("drug_name", keyword).or().likeRight("pinyin_code", keyword));
        }
        return new ResultInfo(baseDrugList);

    }

    @PostMapping("/add")
    public ResultInfo add(@RequestBody @Validated(Add.class) BaseDrug baseDrug)
    {
        AssertUtil.isTrue(!baseDrugService.save(baseDrug), "药品添加失败");
        return new ResultInfo();
    }

    @PostMapping("/update")
    public ResultInfo update(@RequestBody @Validated(Update.class) BaseDrug baseDrug)
    {
        AssertUtil.isTrue(!baseDrugService.updateById(baseDrug), "药品更新失败");
        return new ResultInfo();
    }


    @PostMapping("/delete/{id}")
    public ResultInfo delete(@PathVariable  String id)
    {
        AssertUtil.isTrue(!baseDrugService.removeById(id), "药品删除失败");
        return new ResultInfo();
    }

    @GetMapping("/get/{id}")
    public ResultInfo getById(@PathVariable  String id)
    {
        BaseDrug baseDrug = baseDrugService.getById(id);
        return new ResultInfo(baseDrug);
    }

}
